package com.xhu.rjsx2.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhu.rjsx2.enums.AppHttpCodeEnum;
import com.xhu.rjsx2.pojo.ResponseResult;
import com.xhu.rjsx2.pojo.User;
import com.xhu.rjsx2.pojo.vo.PageVO;
import com.xhu.rjsx2.pojo.vo.UserVO;
import com.xhu.rjsx2.service.UserService;
import com.xhu.rjsx2.mapper.UserMapper;
import com.xhu.rjsx2.util.BeanCopyUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author ZQ
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-05-08 21:02:40
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{



    @Override
    public ResponseResult login(String username,String password,String role) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username)
                .eq(User::getRole,role);
        User user = getOne(queryWrapper);
        if (BeanUtil.isEmpty(user)) return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())){
            user.setLastLoginTime(DateUtil.parse(LocalDateTime.now().toString()));
            UserVO userVO = BeanCopyUtils.copyBeanSingle(user, UserVO.class);
            return ResponseResult.okResult(userVO);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
    }

    @Override
    public PageVO listAllUserPage(Integer pageNum, Integer pageSize,String name,String phone,Integer age) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StrUtil.isBlankIfStr(name),User::getName,name)
                .like(!StrUtil.isBlankIfStr(phone),User::getPhone,phone)
                .eq(!StrUtil.isBlankIfStr(age),User::getAge,age);
        Page<User> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);
        List<UserVO> memberVOList = BeanCopyUtils.copyBeanList(page.getRecords(), UserVO.class);
        return new PageVO(memberVOList, page.getTotal());
    }

}




